package com.frain.springcloud.user.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.frain.springcloud.common.APPConstant;
import com.frain.springcloud.common.XStreamUtil;
import com.frain.springcloud.response.message.ResponseTextMessage;
import com.frain.springcloud.user.entity.CodeState;
import com.frain.springcloud.user.entity.SecondOpenId;
import com.frain.springcloud.user.entity.UserInfo;
import com.frain.springcloud.util.HttpRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    protected static final Logger logger = LoggerFactory.getLogger(UserController.class);

    private String[] errorCode = new String[] { "10003", "10004", "10005", "10006", "10007", "10008", "10009", "10010",
            "10011", "10012", "10013", "10014", "10015", "10016" };

    // 第二步获取用户openId
    private static final String WEB_AUTHORI_URL_PREFIX = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
            + APPConstant.APP_ID + "&secret=" + APPConstant.APP_SECERT + "&code=";
    // 第二步获取用户openId
    private static final String WEB_AUTORI_URL_SUFFER = "&grant_type=authorization_code";

    // 第四部获取用户信息前缀url
    private static final String WEB_GET_USER_URL_PREFIX = "https://api.weixin.qq.com/sns/userinfo?access_token=";
    // 第四部获取用户信息中url
    private static final String WEB_GET_USER_URL_MIDDLE = "&openid=";
    // 第四部获取用户信息后url
    private static final String WEB_GET_USER_URL_SUPFFER = "&lang=zh_CN";

    @RequestMapping("/accessUser")
    public void accessUser(CodeState codeState, HttpServletRequest request, HttpServletResponse response) {

        logger.info("UserController  获取用户code=" + codeState);

        if (codeState != null && !Arrays.asList(errorCode).contains(codeState.getCode())) {
            String secodePath = WEB_AUTHORI_URL_PREFIX + codeState.getCode() + WEB_AUTORI_URL_SUFFER;

            String json = HttpRequest.sendGet(secodePath, "", null);

            logger.info("UserController  获取用户openId" + json);

            SecondOpenId secondOpenId = JSONObject.parseObject(json, SecondOpenId.class);
            try {

                String getUserUrl = WEB_GET_USER_URL_PREFIX + secondOpenId.getAccess_token() + WEB_GET_USER_URL_MIDDLE
                        + secondOpenId.getOpenid() + WEB_GET_USER_URL_SUPFFER;
                String userJson = HttpRequest.sendGet(getUserUrl, "", null);

                logger.info("UserController  获取用户信息 " + userJson);

                UserInfo userInfo = JSONObject.parseObject(userJson, UserInfo.class);

                UserMapUtil.addUserInfo(userInfo.getOpenid(), userInfo);

                sendResponseSuccess(response, userInfo);

            }
            catch (Exception e) {
                logger.info("UserController  失败  exception=" + e.getMessage());

                sendResponseFailure(response, UserInfo.defaultUser(secondOpenId.getOpenid()));
            }

        }

    }

    @RequestMapping("/findUser")
    public void findUser(CodeState codeState, HttpServletRequest request, HttpServletResponse response) {

        logger.info("UserController  获取用户code=" + codeState);

        if (codeState != null && !Arrays.asList(errorCode).contains(codeState.getCode())) {
            String secodePath = WEB_AUTHORI_URL_PREFIX + codeState.getCode() + WEB_AUTORI_URL_SUFFER;

            String json = HttpRequest.sendGet(secodePath, "", null);

            logger.info("UserController  获取用户openId" + json);

            SecondOpenId secondOpenId = JSONObject.parseObject(json, SecondOpenId.class);
            try {
                UserInfo user = UserMapUtil.getUser(secondOpenId.getOpenid());
                if (user != null) {
                    logger.info("UserController  获取用户 user=" + user);
                    sendResponseSuccess(response, user);
                    return;
                }

                String getUserUrl = WEB_GET_USER_URL_PREFIX + secondOpenId.getAccess_token() + WEB_GET_USER_URL_MIDDLE
                        + secondOpenId.getOpenid() + WEB_GET_USER_URL_SUPFFER;
                String userJson = HttpRequest.sendGet(getUserUrl, "", null);

                logger.info("UserController  获取用户信息 " + userJson);

                UserInfo userInfo = JSONObject.parseObject(userJson, UserInfo.class);

                UserMapUtil.addUserInfo(userInfo.getOpenid(), userInfo);

                sendResponseSuccess(response, userInfo);

            }
            catch (Exception e) {
                logger.info("UserController  失败  exception=" + e.getMessage());

                sendResponseFailure(response, UserInfo.defaultUser(secondOpenId.getOpenid()));
            }

        }

    }

    private void sendResponseFailure(HttpServletResponse response, UserInfo userInfo) {

        String context = "获取信息失败";

        sendResponse(response, context, userInfo.getOpenid());

    }

    private void sendResponse(HttpServletResponse response, String context, String openId) {
        ResponseTextMessage textMessage = new ResponseTextMessage();
        textMessage.setContent(context);
        textMessage.setCreateTime(new Date().getTime());
        textMessage.setFromUserName(APPConstant.APP_NAME);
        textMessage.setMsgType("text");
        textMessage.setToUserName(openId);

        String xml = XStreamUtil.textMessagToXml(textMessage);
        logger.info("信息转成xml的值为:" + xml);

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(xml);
            writer.flush();

        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (null != writer) {
                writer.close();
                writer = null;
            }
        }
    }

    private void sendResponseSuccess(HttpServletResponse response, UserInfo userInfo) {
        String context = "name=" + userInfo.getNickname() + "-" + userInfo.getCountry();

        sendResponse(response, context, userInfo.getOpenid());

    }

}
